from rest_framework import status
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKUImage, SKU

# ModelViewSet提供了所有的 增删改查  list  Retrieve Create、Updaten、Destory
from apps.meiduo_admin.serializers.image import SKUImageSerializer, SKUSerializer
from apps.meiduo_admin.utils import PageNum


class SKUImageView(ModelViewSet):
    # 序列化器
    serializer_class = SKUImageSerializer
    # 查询集
    queryset = SKUImage.objects.all()

    # 添加分页类
    pagination_class = PageNum

    def create(self, request, *args, **kwargs):
        # 视图的create 处理所有逻辑 并且返回响应
        # 1接受参数
        image = request.data.get('image')
        sku_id = request.data.get('sku')
        image_data = image.read()  # 获取图片 的二进制数据
        # 2校验参数
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 3保存数据
        # 上传的fdfs
        from fdfs_client.client import Fdfs_client
        client = Fdfs_client('utils/fastdfs/client.conf')
        result = client.upload_by_buffer(image_data)
        # {'Remote file_id': 'group1/M00/00/00/wKjlhFsTgJ2AJvG_AAAyZgOTZN0850.jpg', 'Uploaded size': '12.00KB',
        #  'Local file name': '/home/python/Desktop/images/0.jpg', 'Storage IP': '192.168.229.132',
        #  'Group name': 'group1', 'Status': 'Upload successed.'}
        if result.get("Status") != 'Upload successed.':
            return Response(status=status.HTTP_400_BAD_REQUEST)

        print("上传图片成功")
        file_id = result.get("Remote file_id")
        print("file_id", file_id)
        # 保存到数据库
        sku_image = SKUImage.objects.create(sku_id=sku_id, image=file_id)
        print("sku_image", sku_image)

        # 4返回响应
        return Response({"id": sku_image.id, "image": sku_image.image.url}, status=status.HTTP_201_CREATED)


# 查询SKU数据库
class SKUListAPIView(ListAPIView):
    # 序列化器
    serializer_class = SKUSerializer
    # 查询集
    queryset = SKU.objects.all()
